package com.atguigu.com.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.com.search.config.GulimallElasticsearchConfig;
import com.atguigu.com.search.constant.EsConstant;
import com.atguigu.com.search.service.MallSearchService;
import com.atguigu.com.search.vo.RequestParm;
import com.atguigu.com.search.vo.ResponseParm;
import com.atguigu.common.To.es.SkuEsModel;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    
    @Autowired
    private RestHighLevelClient client;
    /**
     * 搜索页面
     * @param requestParm
     * @return
     */
    @Override
    public ResponseParm search(RequestParm requestParm) {
        //动态构建出查询需要的dsl语句
        ResponseParm result = null;
        //准备检索请求
        SearchRequest searchRequest = BuildSearchRequest(requestParm);

        try {
            //执行检索请求
            SearchResponse search = client.search(searchRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);

            result = buildSearchResult(search,requestParm);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }



    /**
     * 构建检索请求
     * @return
     */
    private SearchRequest BuildSearchRequest(RequestParm requestParm) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //构建dsl检索语句


        /**
         * 模糊匹配
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //1.1模糊查询keywords
        if (!StringUtils.isEmpty(requestParm.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",requestParm.getKeyword()));
        }
        //1.2filter查询
        if (requestParm.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",requestParm.getCatalog3Id()));
        }
        //品牌id
        if (requestParm.getBrandId()!=null&&requestParm.getBrandId().size()>0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",requestParm.getBrandId()));
        }
        //是否有库存
        if (requestParm.getHasStock()==1){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("hasStock",false));
        }

        //价格区间
        if (!StringUtils.isEmpty(requestParm.getSkuPrice())){
            String[] split = requestParm.getSkuPrice().split("_");
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            if (split.length==2){
                rangeQuery.gte(split[0]).lte(split[1]);
            }else if (split.length==1){
                if (requestParm.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(split[0]);
                }else {
                    rangeQuery.gte(split[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        //按照属性进行过滤 嵌入式查询
        if (requestParm.getAttrs()!=null&&requestParm.getAttrs().size()>0){
            //构建查询条件
            List<String> attrs = requestParm.getAttrs();
            for (String attr : attrs) {
                BoolQueryBuilder nestebuilder = QueryBuilders.boolQuery();

                String[] split = attr.split("_");
                String s = split[0];//检索属性id
                String[] split1 = split[1].split(":"); //检索属性的值
                nestebuilder.must(QueryBuilders.termQuery("attrs.attrId",s));
                nestebuilder.must(QueryBuilders.termsQuery("attrs.attrValue",split1));

                NestedQueryBuilder attrs1 = QueryBuilders.nestedQuery("attrs", nestebuilder, ScoreMode.None);
                boolQueryBuilder.filter(attrs1);
            }
        }
        searchSourceBuilder.query(boolQueryBuilder);

        //排序
        if (!StringUtils.isEmpty(requestParm.getSort())){
            String sort = requestParm.getSort();
            String[] split = sort.split("_");
            SortOrder sortOrder = split[1].equalsIgnoreCase("asc")? SortOrder.ASC:SortOrder.DESC;

            searchSourceBuilder.sort(split[0],sortOrder);
        }
        //分页
        searchSourceBuilder.from((requestParm.getPageNum()-1)*EsConstant.PRODUCT_SIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_SIZE);
        //高亮
        if (!StringUtils.isEmpty(requestParm.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            searchSourceBuilder.highlighter(builder);
        }

        /**
         * 聚合分析
         */
        //品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);
//        //分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);
//        //属性聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");

        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));

        nested.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(nested);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        String s = searchSourceBuilder.toString();
        System.out.println("查询"+s);

        return searchRequest;
    }

    /**
     * 搜索结果集
     * @param search
     * @return
     */
    private ResponseParm buildSearchResult(SearchResponse search,RequestParm parm) {
        ResponseParm requestParm = new ResponseParm();
        SearchHits hits = search.getHits();
        //封装商品信息
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits()!=null&&hits.getHits().length>0){
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //获取高亮显示
                if (!StringUtils.isEmpty(parm.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                skuEsModels.add(skuEsModel);
            }
        }
        //获取BrandVo信息
        List<ResponseParm.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = search.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> buckets = brand_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            ResponseParm.BrandVo brandVo = new ResponseParm.BrandVo();
            //获取id
            String keyAsString = bucket.getKeyAsString();
            brandVo.setBrandId(Long.parseLong(keyAsString));
            //获取名字
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String keyAsString1 = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(keyAsString1);
            //获取图片信息
            ParsedStringTerms brand_name_img = bucket.getAggregations().get("brand_img_agg");
            String keyAsString2 = brand_name_img.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(keyAsString2);

            brandVos.add(brandVo);
        }
        //获取分类聚合
        List<ResponseParm.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = search.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets1 = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets1) {
            ResponseParm.CatalogVo catalogVo = new ResponseParm.CatalogVo();
            //获取id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            //获取名字
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String keyAsString1 = brand_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(keyAsString1);
            catalogVos.add(catalogVo);
        }
        //获取属性聚合
        List<ResponseParm.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = search.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            ResponseParm.AttrVo attrVo = new ResponseParm.AttrVo();
            long id = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(id);

            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String keyAsString = attr_name_agg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(keyAsString);

            ParsedStringTerms  attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> collect = attr_value_agg.getBuckets().stream().map(item -> {
                String keyAsString1 = item.getKeyAsString();
                return keyAsString1;
            }).collect(Collectors.toList());
            attrVo.setAttrValue(collect);
            attrVos.add(attrVo);
        }

        requestParm.setProduct(skuEsModels);
        //设置总记录数
        long value = hits.getTotalHits().value;
        requestParm.setTotal(value);
        //设置总页码
        requestParm.setTatalPage((int) (value/EsConstant.PRODUCT_SIZE==0?value/EsConstant.PRODUCT_SIZE:(value/EsConstant.PRODUCT_SIZE+1)));
        //设置当前页
        requestParm.setPageNum(parm.getPageNum());

        requestParm.setAttrVos(attrVos);
        requestParm.setBrandVos(brandVos);
        requestParm.setCatalogVos(catalogVos);

        return requestParm;
    }

}
